"""
用户模型
"""
from sqlalchemy import Column, Integer, String, Enum, DateTime
from sqlalchemy.sql import func
from app.models.base import Base
from typing import Optional

class User(Base):
    """用户表模型"""
    __tablename__ = 't_users'
    
    id = Column(Integer, primary_key=True, autoincrement=True, comment='用户ID')
    username = Column(String(50), unique=True, nullable=False, comment='用户名')
    password = Column(String(255), nullable=False, comment='密码(加密存储)')
    name = Column(String(100), nullable=True, comment='真实姓名')
    email = Column(String(100), nullable=True, comment='邮箱')
    role = Column(Enum('admin', 'user', name='user_role_enum'), nullable=False, default='user', comment='角色')
    avatar = Column(String(255), nullable=True, comment='头像')
    status = Column(Integer, nullable=False, default=1, comment='状态: 1-启用, 0-禁用')
    last_login_time = Column(DateTime, nullable=True, comment='最后登录时间')
    last_login_ip = Column(String(45), nullable=True, comment='最后登录IP')
    created_at = Column(DateTime, nullable=False, default=func.now(), comment='创建时间')
    updated_at = Column(DateTime, nullable=False, default=func.now(), onupdate=func.now(), comment='更新时间')
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            'id': self.id,
            'username': self.username,
            'name': self.name,
            'email': self.email,
            'role': self.role,
            'avatar': self.avatar,
            'status': self.status,
            'last_login_time': self.last_login_time.isoformat() if self.last_login_time else None,
            'last_login_ip': self.last_login_ip,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }